<template>
  <div>
    <a-table
      :pagination="false"
      :row-key="(record) => record.code"
      :columns="columns"
      :data-source="data"
      :scroll="{ x: 1500 }"
      :rowExpandable="(record) => record.isShowIcon"
      class="components-table-demo-nested"
    >
      <template #bodyCell="{ column, record }">
        <!-- 文件名称 -->
        <template v-if="column.dataIndex == 'name'">
          <div>
            <a-input :bordered="false" :disabled="true" v-model:value="record.name" />
          </div>
        </template>

        <!-- 文件类型 -->
        <template v-if="column.dataIndex == 'directoryId'">
          <div>
            <a-tree-select
              :bordered="false"
              :disabled="true"
              v-model:value="record.directoryId"
              :allow-clear="false"
              :field-names="{ label: 'name', value: 'id', children: 'children' }"
              tree-default-expand-all
              :tree-data="treeDataType"
              tree-node-filter-prop="name"
            >
            </a-tree-select>
          </div>
        </template>

        <!-- 保密等级 -->
        <!-- <template v-if="column.dataIndex == 'securityLevel'">
          <div>
            <a-cascader v-model:value="record.securityLevel" :bordered="false" :disabled="true" :options="LevelOptions" :allowClear="false" />
          </div>
        </template> -->

        <!-- 是否文件模板 -->
        <template v-if="column.dataIndex == 'isTemplate'">
          <div>
            <a-cascader v-model:value="record.isTemplate" :bordered="false" :disabled="true" :options="templateOptions" :allowClear="false" />
          </div>
        </template>

        <!-- 文件负责人 -->
        <template v-if="column.dataIndex == 'principalId'">
          <div>
            <a-select
              v-model:value="record.principalId"
              :bordered="false"
              :disabled="true"
              :options="subjectOptions"
              :allowClear="false"
              :field-names="{
                label: 'nickName',
                value: 'id'
              }"
            />
          </div>
        </template>

        <!-- 文件会签人 -->
        <!-- <template v-if="column.dataIndex == 'counterSignIds'">
          <div>
            <a-select
              v-model:value="record.counterSignIds"
              :bordered="false"
              :disabled="true"
              :options="subjectOptions"
              :allowClear="true"
              mode="multiple"
              :field-names="{
                label: 'nickName',
                value: 'id'
              }"
            />
          </div>
        </template> -->

        <!-- 关键字 -->
        <template v-if="column.dataIndex == 'keyword'">
          <div>
            <a-input v-model:value="record.keyword" :bordered="false" :disabled="true" />
          </div>
        </template>

        <!-- 主要内容 -->
        <template v-if="column.dataIndex == 'mainContent'">
          <div>
            <a-input v-model:value="record.mainContent" :bordered="false" :disabled="true" />
          </div>
        </template>

        <!-- 申请原因 -->
        <template v-if="column.dataIndex == 'applyReason'">
          <div>
            <a-input v-model:value="record.applyReason" :bordered="false" :disabled="true" />
          </div>
        </template>

        <!-- 操作项 -->
        <template v-else-if="column.key === 'operation' && ['SIGN'].includes(route.query.showType)">
          <span @click="onAnnotations(record)" class="form-table-actions">批注</span>
        </template>
      </template>
      <!-- 必填选项 -->

      <!-- 嵌套子表格插槽 -->
      <template #expandedRowRender="{ record }">
        <a-table :columns="innerColumns" :data-source="record.versions" :pagination="false">
          <template #bodyCell="{ column, record, text }">
            <template v-if="column.dataIndex === 'remark'">
              <a-input style="margin: -5px 0" v-model:value="record.remark" :bordered="false" :disabled="true" />
            </template>
            <template v-if="column.dataIndex === 'attachmentFile' && ['AUDIT'].includes(route.query.showType)">
              <span style="color: #02a7f0; cursor: pointer" @click="previewFile(record)">{{ text }}</span>
            </template>
          </template>
        </a-table>
      </template>
    </a-table>
    <!-- <OnlineEditingIndex :isShow="editorConfig.isShow"></OnlineEditingIndex> -->
  </div>
</template>

<script setup lang="ts">
import { type TreeSelectProps, type CascaderProps, message } from 'ant-design-vue';
import OnlineEditingIndex from './onlineEditingIndex.vue';
import { onMounted, ref } from 'vue';
import { fileTree } from '@/config/api/publicFile';
import { fileGet, fileInfo } from '@/config/api/documentApplication';
import { treeDataSubject } from '@/config/api/documentApplication';
import { getPreviewFileUrl } from '@/config/api/resourceFileInfo';
import { useRoute, useRouter } from 'vue-router';
import { nextTick } from 'process';
import { changeByte } from '@/utils/common';

const route: any = useRoute();
const router = useRouter();
const data: any = ref([]);
const newArr = ref([]);
const editorConfig = ref({
  isShow: false
});
const emit = defineEmits(['dataType']);
// 初始化赋值
getViewData();
function getViewData() {
  Promise.all([
    fileGet(route.query.id),
    fileTree({
      name: ''
    }),
    treeDataSubject({
      parentId: 0
    })
  ]).then(([fileGetRes, fileTreeRes, treeDataSubjectRes]) => {
    nextTick(() => {
      emit('dataType', fileGetRes.data?.type);
    });
    const result = fileGetRes.data?.applyLists;
    result?.map((item) => {
      newArr.value = [];
      item.isTemplate = [item.isTemplate];
      // item.counterSignIds = filterData(item.countersignResps);
      if (item.attachmentFile === null) {
        item.isShowIcon = false;
      } else {
        item.isShowIcon = true;
        if (item.versions !== null && item.versions.length !== 0) {
          item.versions.forEach((itemSize) => {
            itemSize.size = `${changeByte(itemSize.size)}`;
          });
        }
      }
    });

    data.value = result;
    getFileTree(fileTreeRes);
    getSubjectTree(treeDataSubjectRes);
  });
}

function filterData(arr) {
  arr.forEach((item) => {
    newArr.value.push(item.countersignId);
  });
  return newArr.value;
}
// 文件类型树状
const treeDataType = ref<TreeSelectProps['treeData']>([]);
function getFileTree(result) {
  if (result.success) {
    treeDataType.value = result.data;
  }
}

// 保密等级下拉
const LevelOptions: CascaderProps['options'] = [
  {
    label: '公开',
    value: 4
  },
  {
    label: '机密',
    value: 2
  },
  {
    label: '绝密',
    value: 1
  },
  {
    label: '秘密',
    value: 3
  }
];

// 是否文件模板
const templateOptions: CascaderProps['options'] = [
  {
    label: '是',
    value: 1
  },
  {
    label: '否',
    value: 0
  }
];

// 文件负责人和文件会签人下拉
const subjectOptions = ref<CascaderProps['options']>([]);
function getSubjectTree(result) {
  if (result.success) {
    subjectOptions.value = result.data;
  }
}

// 文件预览
const previewFile = (record) => {
  console.log(record);
  const params = {
    id: record.id,
    expires: 2,
    timeUnit: 'HOURS'
  };
  getPreviewFileUrl(params).then((result) => {
    if (result && result.success) {
      window.open(result.data);
    }
  });
};

const columns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 70, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '文件编码', dataIndex: 'code', key: 'code', width: 150 },
  { title: '文件类型', dataIndex: 'directoryId', key: 'directoryId', width: 150 },
  { title: '版本号', dataIndex: 'version', key: 'version', width: 150 },
  // { title: '保密等级', dataIndex: 'securityLevel', key: 'securityLevel', width: 150 },
  { title: '是否文件模板', dataIndex: 'isTemplate', key: 'isTemplate', width: 150 },
  { title: '文件负责人', dataIndex: 'principalId', key: 'principalId', width: 200 },
  // { title: '文件会签人', dataIndex: 'counterSignIds', key: 'counterSignIds', width: 150 },
  { title: '关键字', dataIndex: 'keyword', key: 'keyword', width: 150 },
  { title: '主要内容', dataIndex: 'mainContent', key: 'mainContent', width: 150 },
  { title: '申请原因', dataIndex: 'applyReason', key: 'applyReason', width: 150 },
  { title: '操作', key: 'operation', width: 200, fixed: 'right' }
];

const innerColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', width: 70, defaultSortOrder: 'descend', customRender: ({ index }) => index + 1 },
  { title: '文件', dataIndex: 'attachmentFile', key: 'attachmentFile', width: 120 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 120 },
  { title: '大小', dataIndex: 'size', key: 'size', width: 120 },
  { title: '上传时间', dataIndex: 'createdTime', key: 'createdTime', width: 150 }
];

const onAnnotations = (record) => {
  fileInfo(record.newVersionId).then((result) => {
    if (result.success) {
      const data = result.data;
      let obj = JSON.stringify({
        key: data.key.replace('|', '_'),
        fileType: data.suffix,
        owner: data.creatorName,
        uploaded: data.createdTime,
        id: data.currentUser,
        name: data.currentUserName
      });
      if (data.suffix !== 'docx' && data.suffix !== 'doc') {
        message.error('失败! 仅支持WORD格式的文件批注');
        return;
      }
      router
        .push({
          name: 'FileOnlineAnnotation',
          query: { information: obj }
        })
        .then(() => {
          router.go(0);
        });
    }
  });
};
</script>
<style lang="less" scoped>
.form-table-heard:before {
  content: '*';
  color: #ff4d4f;
}
.form-table-actions {
  color: #005aea;
  cursor: pointer;
  margin-right: 10px;
}
.promptIcon {
  cursor: pointer;
  color: #005aea;
}
/deep/ .ant-input {
  color: #000;
}
/deep/ .ant-select-selection-item {
  color: #000 !important;
}
/deep/ .ant-select-arrow {
  display: none;
}
/deep/ .ant-select-selection-item {
  border-color: #fff !important;
}
</style>
